<template>
   <section class="Rights">
   	  	<el-form label-position="top" :inline="true" v-model="filter" class="demo-form-inline">
            <el-row>
                <el-col :span="4">
                    <el-form-item label="品牌名称">
		                <el-autocomplete
					      class="inline-input"
					      v-model="filter.brandName"
					      :fetch-suggestions="querySearch"
					      placeholder="请选择品牌名称"
					      @select="handleSelect"
					      size="small"
					    ></el-autocomplete>
				    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="Cookie">
                        <el-input placeholder="Cookie" v-model="filter.cookie" size="small"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="最近一次抓取结果:">
		                <el-select v-model="filter.lastStatus" size="small">
                            <el-option label="全部" value=""></el-option>
                            <el-option label="成功" value="1"></el-option>
                            <el-option label="失败" value="-1"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
              	<el-col :span="4">
                    <el-form-item label="添加时间:" width="100">
                        <el-date-picker
                                size="small"
                                style="width: 100%;"
                                v-model="gmtCreateInterval"
                                type="datetimerange"
                                :picker-options="pickerOptions1"
								start-placeholder="开始日期"
								end-placeholder="结束日期">
                        </el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="最近一次抓取时间:" width="100">
                        <el-date-picker
                            size="small"
                            style="width: 100%;"
                            v-model="lastTimeInterval"
                            :picker-options="pickerOptions1"
                            type="datetimerange"
							start-placeholder="开始日期"
							end-placeholder="结束日期">
                        </el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24" class="action_col">
                    <el-form-item class="action_button_group_open">
                        <el-button size="small" type="primary" @click="empty"><i class="fa fa-trash-o fa-lg"></i> 清空筛选条件
                        </el-button>
                        <el-button size="small" type="primary" @click="submitSearch()" icon="el-icon-search">查询</el-button>
                    </el-form-item>
                </el-col>
            </el-row>  
            <el-row>
		        <el-button size="small" icon="el-icon-plus" @click="addNew">添加</el-button>
		        <el-button size="small" @click="submitSearch()"><i class="fa fa-refresh"></i> 刷新</el-button>
		    </el-row>
            <el-row class="margin-table">
                <el-table :data="tableList" v-model="tableList" border style="width: 100%;">
	                <el-table-column prop="brandName"  label="品牌名称" align='center'></el-table-column>
	                <el-table-column prop="cookie"  label="Cookie" align='center'>
	                	<template scope='scope'>
		                    <div @click="($event)=>{
		                    handleEdit($event,scope);}">
			                    <div class="words">
			                    	<el-popover trigger="hover" placement="top">
			                        	<p style="max-width:600px;word-wrap: break-word;">{{ scope.row.cookie}}</p>
			                            <div slot="reference" class="name-wrapper">
			                               {{ scope.row.cookie.length>=50?scope.row.cookie.slice(0,50)+'...':scope.row.cookie }}
			                            </div>
			                    	</el-popover> 
			                    </div>
				                <div class="input_text" style="display:none;position: relative;">
				                    <input :id="scope.row.id" class="el-input__inner"  type="text" :value="scope.row.cookie"  @blur="($event)=>{
				                      bluring($event,scope);}" autocomplete="off"/> 
				                    <i class="el-input__icon el-icon-close" @click="clearContext(scope,$event)"></i>
				                </div>
		                	</div>
		                </template>
	                </el-table-column>
	                <el-table-column prop="lastStatus"  label="最近一次抓取结果" align='center'></el-table-column>
	                <el-table-column prop="gmtCreateString" label="添加时间" align='center'></el-table-column>
	                <el-table-column prop="lastTimeString" label="最近一次抓取时间" align='center' ></el-table-column>
	                <el-table-column prop="option" label="操作" align='center' width="180" fixed="right">
	                    <template scope="scope">
	                    	<el-button size="mini" type="primary" icon="el-icon-setting" v-if="scope.row.grabStatus==1" @click="catchCookie(scope.$index, scope.row)">抓取</el-button>
	                    	<el-button size="mini" type="primary" icon="el-icon-setting" v-else :disabled="true">抓取</el-button>
	                        <el-button size="mini" type="danger" icon="el-icon-delete" @click="del(scope.$index, scope.row)">删除</el-button>
	                    </template>
	                </el-table-column>
                </el-table>
            </el-row>
            <el-dialog title="添加品牌信息" :visible.sync="dialogFormVisible" @close="resetForm(addForm)">
		        <div class="module-opera-top" >
		            <el-form :model="addForm" :rules="rules" ref="addForm" label-width="130px" >
		            	<el-row>
				            <el-form-item label="品牌名称" prop='name'>
				                <el-autocomplete
							      class="inline-input"
							      v-model="addForm.name"
							      :fetch-suggestions="querySearch"
							      placeholder="请选择品牌名称"
							      @select="handleSelect1"
							      style='width: 265px;'
							    ></el-autocomplete>
				            </el-form-item>
			            </el-row>
			            <el-row>
				            <el-form-item label="Cookie:" prop="Cookie">
				                <el-input type="textarea" v-model="addForm.Cookie" style="width: 265px;"></el-input>
				            </el-form-item>
			            </el-row>
			            <div class="bottom-btn" style="text-align: center">
	                        <el-button  type="primary" class="fa fa-save" size="small" @click="submitForm(addForm)">保存</el-button>
	                        <el-button  type="danger" class="fa fa-sign-out" size="small" @click="resetForm(addForm)">退出</el-button>
	                    </div>
		            </el-form>
		        </div>
	        </el-dialog>
		    <el-row class="paging" style='margin-top: 40px;'>
		        <el-pagination
                  @current-change="handleCurrentChange"
                  @size-change="handleSizeChange"
                  :current-page="currentPage"
                  :page-sizes="[10, 20, 50]"
                  :page-size="pageSize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="totalCount">
		        </el-pagination> 
      		</el-row>
   	  	</el-form>
   </section>
</template>

<script>
	import Vue from 'vue'
	import {mapGetters} from 'vuex'
	import {Row, Col, Form, FormItem, Button ,Select,Option,DatePicker,Table,Pagination,TableColumn,Input,Tabs,TabPane,Message,MessageBox,Dialog,Popover,Autocomplete} from 'element-ui'
	import {getDate} from '../../utils/auth'
	import { RIGHTS_TOTALCOUNT, RIGHTS_CURRENTPAGE, RIGHTS_PAGESIZE } from '../../store/mutation-types/rights/index.js'

    Vue.use(Row);
    Vue.use(Col);
    Vue.use(Form);
    Vue.use(FormItem);
    Vue.use(Button);
    Vue.use(Select);
    Vue.use(Input);
    Vue.use(Option);
    Vue.use(DatePicker);
    Vue.use(Table);
    Vue.use(Tabs);
    Vue.use(TabPane);
    Vue.use(TableColumn);
    Vue.use(Pagination);
    Vue.use(Dialog)
    Vue.use(Popover)
    Vue.use(Autocomplete)
    
    Vue.prototype.$message = Message;
    Vue.prototype.$confirm = MessageBox.confirm;
    export default {
    	head(){
            return {
                title: "维权抓取设置",
                meta: [
                    { hid: 'managerights', name: 'managerights', content: 'managerights'}
                ]
            }
        },
        data() {
            return {
                tabName: '维权抓取设置',
                handleFlag:false,
                filter:{
	      			brandName:'',//品牌名称
	      			cookie:'',//cookie
	      			lastStatus:'',//最近一次抓取结果
					gmtCreateBegin: '', //添加时间开始
                    gmtCreateEnd: '',  //添加时间结束
                    lastTimeBegin: '',//最近一次抓取时间开始
	      			lastTimeEnd: '',//最近一次抓取时间结束
	      			pageSize: 50, // 每页条数
					pageNum: 1
      		    },
      		    gmtCreateInterval:[],//添加时间 
      		    lastTimeInterval:[],//最近一次抓取时间
      		    options:[],
      		    tableList:[],
      		    sauronBrandCookieId:'',
		        addForm:{
		        	name:'',
		        	Cookie:''
		        },
		        modelName:'',
		        rules: {
		            name: [
		              	{ required: true, message: '请选择品牌名称', trigger:'change'}
		            ],
		            Cookie: [
			            { required: true, message: '请填写Cookie', trigger: 'blur' }
			        ]
		        },
		        dialogFormVisible:false,
		        clearContentFlag: false,
		        listData:[],
		        brandSelectId:'',
		        brandSelectName:'',
		        searchId: '',
		        pickerOptions: {
                    disabledDate(time) {
                        return time.getTime() < Date.now() - 8.64e7;
                    }
                },
		        pickerOptions1: {
                    disabledDate(time) {
                        return time.getTime() > Date.now();
                    }
                }
            };
        },
        methods: {
        	querySearch(queryString, cb) {
		        var restaurants = this.restaurants;
		        var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
		        //调用 callback 返回建议列表的数据
		        cb(results);
		    },
		    createFilter(queryString) {
		        return (restaurant) => {
		          return (restaurant.value.indexOf(queryString.toLowerCase()) === 0);
		        };
		    },
		    loadAll(){//模糊搜索受众名称
		    	this.$store.dispatch("getRightsBrandsList").then(res=>{
            		if(res && res.data.successed){
            			var list=res.data.data;
		      		    for(let i=0,len=list.length;i<len;i++ ){
		      		    	this.listData[i]={};
		      		    	this.listData[i].value=list[i].brandName;
		      		    	this.listData[i].id=list[i].id.toString();
		      		    }
	      		    }
	    		}).catch((error) => {})
            	return this.listData
		    },
		    handleSelect(item){		
		    	this.searchId=item.id;
		    },
        	handleCurrentChange(val) {
        		this.$store.commit('RIGHTS_CURRENTPAGE',{currentPage:val});
        		this.getSearchCookieList()
	        },
	        handleSizeChange(val) {
	        	this.$store.commit('RIGHTS_PAGESIZE',{pageSize:val})
				this.getSearchCookieList();
	        },
            empty(){//清空筛选条件
            	let pageSize = this.filter.pageSize;
                let pageNum = this.filter.pageNum;
	    		this.filter = {
	    			brandName:'',//品牌名称
	      			cookie:'',//cookie
	      			gmtCreateBegin: '', //添加时间开始
                    gmtCreateEnd: '',  //添加时间结束
                    lastTimeBegin: '',//最近一次抓取时间开始
	      			lastTimeEnd: '',//最近一次抓取时间结束
	      			lastStatus:'',//最近一次抓取结果
	      			pageSize: pageSize, // 每页条数
					pageNum: pageNum
	    		}
	    		this.searchId='',
	    		this.gmtCreateInterval=[],
	    		this.lastTimeInterval=[];
	    		this.$store.commit('RIGHTS_SEARCH_BRANDNAME',{brandName:this.filter.brandName})
            	this.$store.commit('RIGHTS_SEARCH_SEARCHID',{searchId:this.searchId})
		        this.$store.commit('RIGHTS_SEARCH_LASTSTATUS',{lastStatus:this.filter.lastStatus})
		        this.$store.commit('RIGHTS_SEARCH_COOKIE',{cookie:this.filter.cookie})
		        this.$store.commit('RIGHTS_SEARCH_GMTCREATEBEGIN',{gmtCreateBegin:this.filter.gmtCreateBegin})
		        this.$store.commit('RIGHTS_SEARCH_GMTCREATEEND',{gmtCreateEnd:this.filter.gmtCreateEnd})
		        this.$store.commit('RIGHTS_SEARCH_LASTTIMEBEGIN',{lastTimeBegin:this.filter.lastTimeBegin})
		        this.$store.commit('RIGHTS_SEARCH_LASTTIMEEND',{brandName:this.filter.lastTimeEnd})
	    	},
	    	submitSearch(){
	    		this.getSearchCookieList();
	    		this.$store.commit('RIGHTS_SEARCH_BRANDNAME',{brandName:this.filter.brandName});
	    		this.$store.commit('RIGHTS_SEARCH_SEARCHID',{searchId:this.searchId});
		        this.$store.commit('RIGHTS_SEARCH_LASTSTATUS',{lastStatus:this.filter.lastStatus});
		        this.$store.commit('RIGHTS_SEARCH_COOKIE',{cookie:this.filter.cookie});
		        this.$store.commit('RIGHTS_SEARCH_GMTCREATEBEGIN',{gmtCreateBegin:this.filter.gmtCreateBegin});
		        this.$store.commit('RIGHTS_SEARCH_GMTCREATEEND',{gmtCreateEnd:this.filter.gmtCreateEnd});
		        this.$store.commit('RIGHTS_SEARCH_LASTTIMEBEGIN',{lastTimeBegin:this.filter.lastTimeBegin});
		        this.$store.commit('RIGHTS_SEARCH_LASTTIMEEND',{brandName:this.filter.lastTimeEnd});
	    	},
	    	getSearchCookieList(){//查询获取列表
	    		if(this.gmtCreateInterval&&this.gmtCreateInterval[0]){
	    			this.filter.gmtCreateBegin = this.gmtCreateInterval[0]?getDate(this.gmtCreateInterval[0],true):'';
                    this.filter.gmtCreateEnd =  this.gmtCreateInterval[1]?getDate(this.gmtCreateInterval[1],true):'';
	    		}else{
					this.filter.gmtCreateBegin = ''
					this.filter.gmtCreateEnd = ''
				}
	    		if (this.lastTimeInterval&&this.lastTimeInterval[0]) {
                    this.filter.lastTimeBegin = this.lastTimeInterval[0]?getDate(this.lastTimeInterval[0],true):'';
                    this.filter.lastTimeEnd = this.lastTimeInterval[1]?getDate(this.lastTimeInterval[1],true):'';
                }else{
                    this.filter.lastTimeBegin =''
                    this.filter.lastTimeEnd = ''
                }
                if(this.filter.brandName==''){
                	this.searchId=''
                }
	    		this.$store.dispatch("getRightsSearchList",{
	    			brandNameLike:this.filter.brandName,
	    			brandId:this.searchId,
	    			cookie:this.filter.cookie,
	    			lastStatus:this.filter.lastStatus,
	    			gmtCreateBegin: this.filter.gmtCreateBegin, //添加时间开始
                    gmtCreateEnd: this.filter.gmtCreateEnd,  //添加时间结束
                    lastTimeBegin: this.filter.lastTimeBegin,//最近一次抓取时间开始
	      			lastTimeEnd: this.filter.lastTimeEnd,//最近一次抓取时间结束
	    			pageNum: this.currentPage,
            		pageSize: this.pageSize
	    		}).then(res=>{
	    			if(!res) {return ;}
	    			let result=res.data;
//	    			this.pagingData.total = result.data.total;
	    			this.$store.commit('RIGHTS_TOTALCOUNT',{totalCount:result.data.total})
	    			if(result.code == 0 && result.data){
	    				this.tableList=result.data.list;
	    				for(var i = 0; i < this.tableList.length; i++){
	    					if(this.tableList[i].lastStatus>0){
								this.tableList[i].lastStatus = "成功"; 
							}else{
								this.tableList[i].lastStatus = "失败"; 
							}
	   					}			
	    			}
	    		}).catch((error) => {})
    	    },
    	    catchCookie(index,row){
    	    	this.$store.dispatch("getRightsbrandCookie",{
    	    		brandId:row.brandId,
    	    		brandName:row.brandName,
    	    		id:row.id,
    	    		cookie:row.cookie
    	    	}).then(res=>{
    	    		if(res && res.data.successed){
    	    			setTimeout(() => {
							this.getSearchCookieList()
                		},1000);
    	    		}
    	    	}).catch((error) => {})
    	    },
    	    del(index,row) {//删除
    	    	this.sauronBrandCookieId = row.id;
    	    	var brandName=row.brandName;
		        this.$confirm('确认删除品牌	'+brandName+'  的抓取设置信息吗？', '提示', {
		            confirmButtonText: '确定',
		            cancelButtonText: '取消',
		            type: 'warning'
		        }).then(() => {
		        	this.sureDelete();
		        }).catch(() => {
		        	this.cancelDelete();         
		        });
            },           
            cancelDelete(){//取消删除
            	this.$message({type: 'info',message: '取消删除！'});
            },           
            sureDelete(){//确认删除
            	this.$store.dispatch("getRightsDelete",{
            		sauronBrandCookieId:this.sauronBrandCookieId
            	}).then(res=>{
            		if(!res) {return ;}
            		if(res && res.data.successed){
	            		this.getSearchCookieList();
	            		this.$message({type: 'success',message: '删除成功!'});
            		}
            	})
            },           
            addNew() {//点击添加按钮
	            this.dialogFormVisible = true;
	            this.modelName=this.addForm.name.toString();
	        },
	        handleSelect1(item){//获取当前选中的品牌id		
		    	this.brandSelectId=item.id;
		    	this.brandSelectName=item.value;
		    	console.log(item.value)
		    },
	        addtableData(){//添加数据到列表
	        	if(this.brandSelectId){
		        	this.$store.dispatch("getRightsAddData",{
		        		brandId:this.brandSelectId,
		        		brandName:this.brandSelectName.replace(/(^\s*)|(\s*$)/g, ""),
		        		cookie:this.addForm.Cookie.replace(/(^\s*)|(\s*$)/g, "")
		        	}).then(res=>{
		        		if(res && res.data.successed){
		        			this.getSearchCookieList();
		        			this.$message({type: 'success',message: '添加成功!'});
		        		}
		        	}).catch(() => {})
	        	}else{
	        		this.$message({type: 'error',message: '请选择品牌名称!'});
	        	}
	        },	        
	        handleEdit (e, scope) { //编辑表格cookie 
			    setTimeout(() => {
					var parentIptNode = this.getIpt(e,scope).parentNode.parentNode;
					var words = parentIptNode.querySelector('.words');
					var iptTxt = parentIptNode.querySelector('.input_text');
					words.style.display = 'none';
					iptTxt.style.display = 'block';
                    this.getIpt(e,scope).focus();  
                },100);
		    },
		    getIpt(e, scope){
		        let input = document.getElementById(scope.row.id)
		        return input
			},
		    bluring (e, scope) {//失去焦点
		        setTimeout(()=>{
				    if(this.clearContentFlag){
					   let input =	this.getIpt(e,scope)
					   input.focus();
					   this.clearContentFlag = false;
					}else{
					   var parentIptNode = this.getIpt(e,scope).parentNode.parentNode;
					   var words = parentIptNode.querySelector('.words');
					    var iptTxt = parentIptNode.querySelector('.input_text');			
					    words.style.display = 'block';
					    iptTxt.style.display = 'none';
					    var index = scope.$index;
					    let v = this.getIpt(e,scope).value.replace(/(^\s*)|(\s*$)/g, "");	 
					    let onlyV=this.tableList[index].cookie.replace(/(^\s*)|(\s*$)/g, "");
					    var name= v == '' ? this.tableList[index].cookie.replace(/(^\s*)|(\s*$)/g, "") : this.getIpt(e,scope).value.replace(/(^\s*)|(\s*$)/g, "");
					    this.getIpt(e,scope).value = name;
						
					    if(this.tableList[index].cookie!=this.getIpt(e,scope).value && name!= this.tableList[index].cookie){
					    	this.getIpt(e,scope).value = name;
//						    words.innerHTML = name;
					    	var brandCookieId=this.tableList[index].id;
							var cookie=name;
						    this.$store.dispatch("getCookieUpdate",{
						   		brandCookieId:brandCookieId,
						   		cookie:cookie
						    }).then(res=>{
						    	if(!res){
						    		this.getIpt(e,scope).value=onlyV;
						    		this.tableList[index].cookie=onlyV;
						    		this.getIpt(e,scope).value=onlyV;
						    	}
						    	if(res && res.data.successed){
						    		this.getIpt(e,scope).value=name;
					    			this.tableList[index].cookie=name;
		        			        this.$message({type: 'success',message: '更新Cookie成功!'});
						    	}else{
						    		this.getIpt(e,scope).value=onlyV;
						    		this.tableList[index].cookie=onlyV;
									this.getIpt(e,scope).value=onlyV;
						    	}
						    }).catch((error) => {})	
					    }
					}
			    }, 500)   
		    },
		    clearContext (scope, e) {//点击X号
		    	var input = this.getIpt(e, scope)
		    	input.value=""
				this.clearContentFlag = true
		        input.focus()	            
		    },
	        submitForm(val,asd) {
	            this.$refs.addForm.validate((valid) => {
		            if (valid) {
		            	this.addtableData();
		            	if(this.brandSelectId){
		            		this.resetForm();
		            	}
		            } else {
		               return false;
		            }
	            })
	        },
	        resetForm(addForm) {
	        	this.dialogFormVisible = false;
		        this.$refs.addForm.resetFields();
		    }
        },
        computed : {
            ...mapGetters({
               'pageTabsList': 'getPageTabsList',
               'currentPage': 'currentPageRights',
               'totalCount': 'totalCountRights',
               'pageSize': 'pageSizeRights',
            })
        },
        mounted() {
            this.restaurants=this.loadAll();
        },
        created(){
            //pageTab
            this.filter.brandName = this.$store.state.rights.brandName;
            this.searchId = this.$store.state.rights.searchId;
	        this.filter.lastStatus = this.$store.state.rights.lastStatus;
	        this.filter.cookie = this.$store.state.rights.cookie;
	        this.filter.gmtCreateBegin = this.$store.state.rights.gmtCreateBegin;
	        this.filter.gmtCreateEnd = this.$store.state.rights.gmtCreateEnd;
	        this.filter.lastTimeBegin = this.$store.state.rights.lastTimeBegin;
	        this.filter.lastTimeEnd = this.$store.state.rights.lastTimeEnd;
	        if(this.filter.gmtCreateBegin.length){
                this.gmtCreateInterval = [new Date(this.filter.gmtCreateBegin),new Date(this.filter.gmtCreateEnd)]
            }
            if(this.filter.lastTimeBegin.length){
                this.lastTimeInterval = [new Date(this.filter.lastTimeBegin),new Date(this.filter.lastTimeEnd)]
            }
            if(process.BROWSER_BUILD) {
                if(this.pageTabsList[this.pageTabsList.length-1].name == 'CRM') {
                    let arr = this.pageTabsList;
                    arr[arr.length-1].name = this.tabName;
                    this.$store.commit('PAGETABSLIST',{data:arr})
                }
            }
            this.getSearchCookieList();
        }
    }
</script>

<style lang="scss">
	.Rights{
		margin-top: 20px;
		a, a:hover, a:focus, a:visited{
			color: #20a0ff;
	    	-webkit-text-decoration-line: underline;
	  		text-decoration-line: underline; 
		}
		.margin-table {
			margin-top: 20px;
			.el-icon-close{padding-right: 8px;position: absolute;top: 0;right: 0;}
			.input_text .el-input__inner{padding-right: 25px;}
		}
		.module-opera-top{
			.el-form-item{margin-bottom: 50px !important;}
		}
		.el-form--inline .el-form-item__label{
			float: left !important;
		}
		.el-form {
			.el-form-item {
				width: 70%
			}
		}
	}
</style>